﻿using Example.Modbus.Kernel;
using Microsoft.Extensions.Logging;
using SuperSocket.Command;
using Xph.Sag.Kernel;

//00 20 E0 69 88
//00 10 01 BD C0
namespace Example.Modbus.Command;

/// <summary>
/// 
/// </summary>
[Command(Name = "ReadId", Key = (byte)0x20)]
public class IdCommand : ICommand<RtuSession, XphPackage>
{
    public async void Execute(RtuSession session, XphPackage package)
    {
        Console.WriteLine(package.Address);
        Console.WriteLine(session.RemoteEndPoint);
        session.Logger.LogDebug("远端设备:{RemoteEndPoint}。回发设备地址:{Address}", session.RemoteEndPoint, package.Address);

        if (package.Address > 254)
        {
            session.Logger.LogDebug("设备返回id：{Address}，超出有效范围0-254。断开连接", package.Address);
            await session.CloseAsync();
            return;
        }
        session.Address = package.Address;

        //await _redis.ConnectAsync();
        //await _redis.SetHashedAsync("OnlineDevice", session.SessionID, new
        //{
        //    EndPoint = session.RemoteEndPoint.ToString(),
        //    Address = session.Address,
        //    OnlineTime = ConvertToUnixTimestamp(session.StartTime.LocalDateTime),
        //    SessionId = session.SessionID
        //});

        ///正确读取到设备address后可以开启session 定时器读取设备数据
        session.BeginReadData();
    }
}
